package org.jasig.cas;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.util.CommonUtils;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.ui.AbstractProcessingFilter;
import org.springframework.security.ui.FilterChainOrder;
import org.springframework.security.util.TextUtils;
import org.springframework.util.Assert;

public class ekingstarProcessingFilter extends AbstractProcessingFilter {
	public static final String CAS_STATEFUL_IDENTIFIER = "_cas_stateful_";
	public static final String CAS_STATELESS_IDENTIFIER = "_cas_stateless_";
	private String proxyReceptorUrl;
	private ProxyGrantingTicketStorage proxyGrantingTicketStorage;
	
	public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
	public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
	public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";
	private String usernameParameter;
	private String passwordParameter;
	public ekingstarProcessingFilter() {
		this.usernameParameter = "ekingstar_username";
		this.passwordParameter = "ekingstar_password";
	}
	@Override
	public Authentication attemptAuthentication(
			HttpServletRequest request)
			throws AuthenticationException {
		
		String errorCode = request.getParameter("errorCode");
		UsernamePasswordAuthenticationToken authRequest;
		Authentication ah;
		if(errorCode!=null||request.getParameter("ticket")==null){
			String username = obtainUsername(request);
			String password = obtainPassword(request);
			if (username == null) {
				username = "";
			}
			if (password == null) {
				password = "";
			}
			username = username.trim();
			authRequest= new UsernamePasswordAuthenticationToken(username, password);
			HttpSession session = request.getSession(false);
			if ((session != null) || (super.getAllowSessionCreation())) {
				request.getSession().setAttribute("SPRING_SECURITY_LAST_USERNAME",
					TextUtils.escapeEntities(username));
			}
			setDetails(request, authRequest);
		}else{
			String username = "_cas_stateful_";
			String password = request.getParameter("ticket");

			if (password == null) {
				password = "";
			}
			 authRequest = new UsernamePasswordAuthenticationToken(
					"_cas_stateful_", password);

			authRequest.setDetails(this.authenticationDetailsSource
					.buildDetails(request));
			
		}
		ah=super.getAuthenticationManager().authenticate(authRequest);
		if(ah.isAuthenticated()){
			request.getSession().setAttribute("_cas_authenticated", true);
		}
		return ah;
		
	}

	@Override
	public String getDefaultFilterProcessesUrl() {
		return "/j_spring_cas_security_check";
	}
	
	public int getOrder() {
		return FilterChainOrder.CAS_PROCESSING_FILTER;
	}
	
	protected boolean requiresAuthentication(HttpServletRequest request,
			HttpServletResponse response) {
		String requestUri = request.getRequestURI();

		if ((CommonUtils.isEmpty(this.proxyReceptorUrl))
				|| (!(requestUri.endsWith(this.proxyReceptorUrl)))
				|| (this.proxyGrantingTicketStorage == null)) {
			return super.requiresAuthentication(request, response);
		}
		try {
			CommonUtils.readAndRespondToProxyReceptorRequest(request, response,
					this.proxyGrantingTicketStorage);
			return false;
		} catch (IOException e) {
		}
		return super.requiresAuthentication(request, response);
	}
	protected String obtainPassword(HttpServletRequest request) {
		return request.getSession().getAttribute(this.passwordParameter)!=null?request.getSession().getAttribute(this.passwordParameter).toString():request.getParameter(SPRING_SECURITY_FORM_PASSWORD_KEY);
	}

	protected String obtainUsername(HttpServletRequest request) {
		return request.getSession().getAttribute(this.usernameParameter)!=null?request.getSession().getAttribute(this.usernameParameter).toString():request.getParameter(SPRING_SECURITY_FORM_USERNAME_KEY);
	}

	protected void setDetails(HttpServletRequest request,
			UsernamePasswordAuthenticationToken authRequest) {
		authRequest.setDetails(this.authenticationDetailsSource
				.buildDetails(request));
	}

	public void setUsernameParameter(String usernameParameter) {
		Assert.hasText(usernameParameter,
				"Username parameter must not be empty or null");
		this.usernameParameter = usernameParameter;
	}

	public void setPasswordParameter(String passwordParameter) {
		Assert.hasText(passwordParameter,
				"Password parameter must not be empty or null");
		this.passwordParameter = passwordParameter;
	}
	String getUsernameParameter() {
		return this.usernameParameter;
	}

	String getPasswordParameter() {
		return this.passwordParameter;
	}
}
